package com.shaoshaohuo.app.ui.ec;

import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.TranslateAnimation;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.shaoshaohuo.app.R;
import com.shaoshaohuo.app.utils.city.Cityinfo;
import com.shaoshaohuo.app.constant.ExtraName;
import com.shaoshaohuo.app.constant.ListViewAction;
import com.shaoshaohuo.app.entity.BaseEntity;
import com.shaoshaohuo.app.entity.EcCategorySecond;
import com.shaoshaohuo.app.entity.EcCategoryThird;
import com.shaoshaohuo.app.entity.EcVarietyEntity;
import com.shaoshaohuo.app.entity.PurchaseHall;
import com.shaoshaohuo.app.entity.PurchaseHallEntity;
import com.shaoshaohuo.app.utils.im.IMFactory;
import com.shaoshaohuo.app.framework.AccountManager;
import com.shaoshaohuo.app.framework.SharedPreferencesHelper;
import com.shaoshaohuo.app.net.HttpRequest.RequestListener;
import com.shaoshaohuo.app.net.RequestService;
import com.shaoshaohuo.app.ui.BaseActivity;
import com.shaoshaohuo.app.adapter.PurchaseListAdapter;
import com.shaoshaohuo.app.view.SelectProductTypePop;
import com.shaoshaohuo.app.view.SelectProductTypePop.OnSelectItemListener;
import com.shaoshaohuo.app.view.TopbarView;
import com.shaoshaohuo.app.view.XListView;
import com.shaoshaohuo.app.view.XListView.IXListViewListener;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenu;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuCreator;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuItem;
import com.shaoshaohuo.app.view.swipemenu.SwipeMenuListView.OnMenuItemClickListener;
import com.shaoshaohuo.app.utils.CityinfoUtil;
import com.shaoshaohuo.app.utils.DeviceHelper;
import com.shaoshaohuo.app.utils.StringHelper;
import com.shaoshaohuo.app.utils.StringUtil;
import com.shaoshaohuo.app.utils.ViewUtil;
import com.umeng.analytics.MobclickAgent;
import com.shaoshaohuo.app.view.citymenu.CascadingMenuPopWindow;
import com.shaoshaohuo.app.view.citymenu.interfaces.CascadingMenuViewOnSelectListener;
import com.shaoshaohuo.app.view.citymenu.entity.Area;

import java.util.ArrayList;
import java.util.List;
	
/**
 * @author: yusonglin
 * @类 说 明:  采购大厅
 * @version 1.0
 * @创建时间：2015年8月31日 上午10:19:42
 * 
 */
public class PurchaseHallActivity extends BaseActivity implements
		OnClickListener, IXListViewListener {

	private static final int SELECT_PRODUCT_TYPE = 1;
	private static final int SELECT_MARKET_CITY = SELECT_PRODUCT_TYPE + 1;

	private TopbarView mTopbarView;

	private TextView mLeftTabText;
	private TextView mCenterTabText;
	private TextView mRightTabText;

	private XListView mListView;

	private PurchaseListAdapter<PurchaseHall> mAdapter;

	private List<PurchaseHall> mDataList = new ArrayList<PurchaseHall>();
	private String bigpid = "";
	private String catid = "";
	private String varieties = "";

	private String cityid = "";

	private String action = ListViewAction.NEW;
	private String cursor = "0";
	private int size = 10;
    private ImageView ivIconHand;

	private EcCategorySecond ecCategorySecond;
	protected List<EcCategoryThird> mVarietyList;
	private SelectProductTypePop selectProductTypePop;
	private Cityinfo selectCity; // 选中的市
	private CascadingMenuPopWindow cascadingMenuPopWindow;
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(new TopbarView(this));
		new Handler().postDelayed(new Runnable() {

			@Override
			public void run() {
				setContentView(R.layout.activity_purchase_hall);
				initData();
				initView();
				setUpView();
                addShade();
				requestData(true);
			}
		}, 200);
	}

    /**
     * 添加遮罩
     */
    private void addShade() {
        if (StringUtil.isEmpty(SharedPreferencesHelper.getString(SharedPreferencesHelper.Field.SHADE_PURCHASE_HALL, ""))) {
            final RelativeLayout markLayout = (RelativeLayout) findViewById(R.id.layout_mark);
            markLayout.setVisibility(View.VISIBLE);
            ivIconHand = (ImageView) findViewById(R.id.icon_hand);
            TranslateAnimation myAnimation_Translate = new TranslateAnimation(ViewUtil.dip2px(this, 220f), ViewUtil.dip2px(this, 113f), 0f, 0f);
            myAnimation_Translate.setDuration(3000);
            myAnimation_Translate.setRepeatCount(Integer.MAX_VALUE);
            ivIconHand.startAnimation(myAnimation_Translate);
            markLayout.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    markLayout.setVisibility(View.GONE);
                    SharedPreferencesHelper.setString(SharedPreferencesHelper.Field.SHADE_PURCHASE_HALL, "true");
                }
            });
        }
    }

    protected void initData() {
		ecCategorySecond = (EcCategorySecond) getIntent().getSerializableExtra(
				ExtraName.ecCategorySecond);
	}

	private void initView() {
		mTopbarView = (TopbarView) this.findViewById(R.id.topbar);

		mLeftTabText = (TextView) this.findViewById(R.id.textview_tab_left);
		mCenterTabText = (TextView) this.findViewById(R.id.textview_tab_center);
		mRightTabText = (TextView) this.findViewById(R.id.textview_tab_right);

		mListView = (XListView) this.findViewById(R.id.listview_data_list);
		mListView.setMenuCreator(new MySwipeMenuCreator());
		mListView.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(int position, SwipeMenu menu, int index) {
				if (AccountManager.getUserId().equals(mDataList.get(position).getUserid())) {
					 return false; 
				 }
				switch (index) {
				case 0:
					IMFactory.openChat(PurchaseHallActivity.this, mDataList.get(position).getUserid());
					break;
				case 1:
					DeviceHelper.callPhone(PurchaseHallActivity.this, mDataList.get(position).getMobile(), mDataList.get(position).getKey());
					break;
				}
				return false;
			}
		});

	}

	private void setUpView() {
		mTopbarView.setCenterText("采购大厅");
		mTopbarView.setLeftView(true, true);

		mLeftTabText.setOnClickListener(this);
		mCenterTabText.setOnClickListener(this);
		mRightTabText.setOnClickListener(this);

		if (ecCategorySecond != null) {
			bigpid = ecCategorySecond.getBigpid();
			catid = ecCategorySecond.getCatid();
			mLeftTabText.setText(ecCategorySecond.getCatname());
			mVarietyList = null;
			if (!ecCategorySecond.getCatname().equals("不限")) {
				getVariety(ecCategorySecond);
			}
		}

		setListView();

	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.textview_tab_left:
			selectProduct();
			break;
		case R.id.textview_tab_center:
			if (mVarietyList == null || mVarietyList.isEmpty()) {
				if (mLeftTabText.getText().toString().equals("分类") || mLeftTabText.getText().toString().equals("不限")) {
					showToast("请选择分类");
				} else {
					showToast("当前分类未细分品种");
				}
				return;
			}
			if (selectProductTypePop == null) {

				selectProductTypePop = new SelectProductTypePop(this);
				selectProductTypePop
						.setOnSelectItemListener(new OnSelectItemListener() {

							@Override
							public void onSelect(List<EcCategoryThird> list) {
								StringBuilder sb = new StringBuilder();
								for (EcCategoryThird item : list) {
									sb.append(item.getCatid() + ",");
								}
								varieties = sb.toString();
								refrensh();
							}
						});
			}
			selectProductTypePop.setData(mVarietyList);
			selectProductTypePop.showLocation(mLeftTabText);

			break;
		case R.id.textview_tab_right:
			selectMarketCity();
			break;
		}
	}

	private void selectMarketCity() {
//		new CascadingMenuPopWindow().showInstance(this, mRightTabText, new NMCascadingMenuViewOnSelectListener());
		if (cascadingMenuPopWindow == null) {
			//向三级menu添加地区数据
			cascadingMenuPopWindow = new CascadingMenuPopWindow(this);
			cascadingMenuPopWindow
					.setMenuViewOnSelectListener(new NMCascadingMenuViewOnSelectListener());
			cascadingMenuPopWindow.showAsDropDown(mRightTabText, 5, 5);
		} else if (cascadingMenuPopWindow != null
				&& cascadingMenuPopWindow.isShowing()) {
			cascadingMenuPopWindow.dismiss();
		} else {
			cascadingMenuPopWindow.showAsDropDown(mRightTabText, 5, 5);
		}
		/*// Intent intent = new Intent(this,SelectProvinceActivity.class);
		// startActivityForResult(intent, SELECT_MARKET_CITY);
		AlertDialog.Builder builder = new Builder(PurchaseHallActivity.this);
		// builder.setView(R.layout.activity_hello);
		View inflate = View.inflate(getBaseContext(), R.layout.sanji, null);
		cityPicker = (CityPicker) inflate.findViewById(R.id.citypicker);
		cityPicker.setOnSelectingListener(new OnSelectingListener() {
			@Override
			public void selected(boolean selected) {

			}
		});
		builder.setView(inflate);
		builder.setPositiveButton("确认", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				selectProvince = cityPicker.getprovince();
				selectCity = cityPicker.getCity();
				mRightTabText.setText(selectCity.getCity_name());
				// selectProvince = (Province)
				// Data.getSerializableExtra(ExtraName.province);
				// selectCity = (City)
				// Data.getSerializableExtra(ExtraName.city);
				refrensh();
			}
		});
		builder.show();*/
	}

	class NMCascadingMenuViewOnSelectListener implements
			CascadingMenuViewOnSelectListener {

		@Override
		public void getValue(Area city, String fullname) {
			mRightTabText.setText(city.getName());
			selectCity = CityinfoUtil.convert(city);
			refrensh();
		}

	}
	private void selectProduct() {
		Intent intent = new Intent(this, ProductTypeActivity.class);
		startActivityForResult(intent, SELECT_PRODUCT_TYPE);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case SELECT_PRODUCT_TYPE:
				EcCategorySecond second = (EcCategorySecond) data
						.getSerializableExtra(ExtraName.ecCategorySecond);
				if (ecCategorySecond != null
						&& !TextUtils.isEmpty(ecCategorySecond.getCatid())
						&& ecCategorySecond.getCatid()
								.equals(second.getCatid())) {
				} else {

					if (ecCategorySecond != null
							&& second.getCatname().equals("不限")
							&& ecCategorySecond.getCatname().equals("不限")) {
						return;
					}
					ecCategorySecond = second;
					bigpid = ecCategorySecond.getBigpid();
					catid = ecCategorySecond.getCatid();
					mLeftTabText.setText(ecCategorySecond.getCatname());
					varieties = "";
					refrensh();
					mVarietyList = null;
					selectProductTypePop = null;
					if (!ecCategorySecond.getCatname().equals("不限")) {
						getVariety(ecCategorySecond);
					}
				}
				break;
			case SELECT_MARKET_CITY:
				/*
				 * selectProvince = (Province)
				 * Data.getSerializableExtra(ExtraName.province); selectCity =
				 * (City) Data.getSerializableExtra(ExtraName.city);
				 * mRightTabText.setText(selectCity.getCityname());
				 */
				refrensh();
				break;
			}
		}
	}

	private void getVariety(EcCategorySecond item) {
		startLoadingDialog();
		RequestService.getInstance().getEcCategoryVariety(this,
				item.getBigpid(), item.getCatid(), EcVarietyEntity.class,
				new RequestListener() {

					@Override
					public void onSuccess(int requestCode, BaseEntity resultData) {
						dismissLoadingDialog();
						if (resultData.isOk()) {
							EcVarietyEntity entity = (EcVarietyEntity) resultData;
							// setVarietyAdapter(entity.getData().getList());
							mVarietyList = entity.getData().getList();
						} else {
							showToast(resultData.getMsg());
						}
					}

					@Override
					public void onFailed(int requestCode, Exception error,
							String msg) {
						dismissLoadingDialog();
						showToast(R.string.please_check_network);
					}
				});
	}

	private void refrensh() {
		mDataList.clear();
		onRefresh();
	}

	private void requestData(boolean isLoading) {
		if (isLoading) {
			startLoadingDialog();
		}

		if (selectCity != null) {
			cityid = selectCity.getId();
		} else {
			cityid = null;
		}

		RequestService.getInstance().getPurchaseList(this, cursor, size + "",
				action, bigpid, catid, varieties, cityid,
				PurchaseHallEntity.class, new RequestListener() {

					@Override
					public void onSuccess(int requestCode, BaseEntity resultData) {
						dismissLoadingDialog();
						if (resultData.isOk()) {
							PurchaseHallEntity entity = (PurchaseHallEntity) resultData;
							List<PurchaseHall> list = entity.getData()
									.getList();
							mDataList.addAll(list);

							if ((mDataList.size() < size)
									|| (action.equals(ListViewAction.HISTORY) && list
											.size() < size)) {
								// mListView.setPullLoadEnable(false);
								mListView.endLoadingMore("没有更多了");
							}
							setAdapter(mDataList);

						} else {
							showToast(resultData.getMsg());
						}
						onLoad();
					}

					@Override
					public void onFailed(int requestCode, Exception error,
							String msg) {
						dismissLoadingDialog();
						showToast(msg);
						onLoad();
					}
				});
	}

	protected void setAdapter(List<PurchaseHall> mDataList2) {
		// if(mDataList2.isEmpty()){
		// mDataList2.add(new SupplyRecord());
		// mDataList2.add(new SupplyRecord());
		// mDataList2.add(new SupplyRecord());
		// mDataList2.add(new SupplyRecord());
		// mDataList2.add(new SupplyRecord());
		// mDataList2.add(new SupplyRecord());
		// mDataList2.add(new SupplyRecord());
		// mDataList2.add(new SupplyRecord());
		// mDataList2.add(new SupplyRecord());
		// mDataList2.add(new SupplyRecord());
		// }
		if (mAdapter == null) {
			mAdapter = new PurchaseListAdapter<PurchaseHall>(this, mDataList2,
					false);
			mListView.setAdapter(mAdapter);
		} else {
			mAdapter.setData(mDataList2);
			// mAdapter.notifyDataSetChanged();
		}
	}

	private void setListView() {
		mListView.setPullLoadEnable(true);
		mListView.setPullRefreshEnable(true);
		mListView.setXListViewListener(this);

		mListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				// PurchaseHall order = (Order)
				// parent.getItemAtPosition(position);
				// Intent intent = new
				// Intent(PurchaseHallActivity.this,OrderDetailShipperActivity.class);
				// intent.putExtra(ExtraName.orderid, order.getBusinessorderid());
				// startActivity(intent);
				PurchaseHall supply = (PurchaseHall) parent
						.getItemAtPosition(position);
				Intent intent = new Intent(PurchaseHallActivity.this,
						PurchaseDetailActivity.class);
				intent.putExtra(ExtraName.id, supply.getId());
				startActivity(intent);
			}
		});
	}

	@Override
	public void onRefresh() {
		// if (mDataList.size() > 0) {
		// cursor = mDataList.get(0).getCursor();
		// } else {
		cursor = "0";
		// }
		mDataList.clear();
		action = ListViewAction.NEW;
		mListView.setPullLoadEnable(true);
		requestData(false);
	}

	@Override
	public void onLoadMore() {
		if (mDataList.size() > 0) {
			cursor = mDataList.get(mDataList.size() - 1).getCursor();
		} else {
			cursor = "0";
		}
		action = ListViewAction.HISTORY;
		requestData(false);
	}

	private void onLoad() {
		mListView.stopRefresh();
		mListView.stopLoadMore();
	}
	@Override
	protected void onDestroy() {
		if (cascadingMenuPopWindow != null) {
			cascadingMenuPopWindow.dismiss();
		}
		super.onDestroy();
	}

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    class MySwipeMenuCreator implements SwipeMenuCreator{
		@Override
		public void create(SwipeMenu menu) {
			SwipeMenuItem imMenu = new SwipeMenuItem(PurchaseHallActivity.this);
			imMenu.setBackground(new ColorDrawable(Color.parseColor("#2eabf1")));
			imMenu.setIcon(R.drawable.icon_chat_left_ad);
			imMenu.setWidth(StringHelper.dip2px(PurchaseHallActivity.this, 70));
			menu.addMenuItem(imMenu);
			SwipeMenuItem callMenu = new SwipeMenuItem(PurchaseHallActivity.this);
			callMenu.setBackground(new ColorDrawable(Color.parseColor("#6dc114")));
			callMenu.setIcon(R.drawable.icon_tel_left_ad);
			callMenu.setWidth(StringHelper.dip2px(PurchaseHallActivity.this, 70));
			menu.addMenuItem(callMenu);
		}
	}
}
